﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercises
{
    public static class Extension
    {
        public static string Substring(this StringBuilder builder, int index, int length)
        {
            if (index >= builder.Length)
            {
                throw new IndexOutOfRangeException();
            }

            if (index + length >= builder.Length || length <= 0)
            {
                throw new ArgumentException("Invalid Length!");
            }

            StringBuilder substring = new StringBuilder(length);
            for (int i = index; i < index + length; i++)
            {
                substring.Append(builder[i]);
            }
            return substring.ToString();
        }

        public static T Map<T>(this IEnumerable<T> enumerable, Func<T, T, T> func)
        {
            if (func == null)
            {
                throw new ArgumentException("Parameter func cannot be null!");
            }

            IEnumerator<T> enumerator = enumerable.GetEnumerator();
            if (!enumerator.MoveNext())
            {
                throw new ArgumentException("Empty enumerable!");
            }

            T result = enumerator.Current;
            while(enumerator.MoveNext())
            {
                result = func(result, enumerator.Current);
            }
            enumerator.Dispose();
            return result;
        }
    }
}
